package com.itheima.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        // 判断访问资源路径是否和登录、注册、展示首页相关
        String[] urls = {"/index.jsp", "/selectAllServlet", "/itemDetailServlet", "/login.html", "/imgs/", "/css/", "/loginServlet", "/register.html", "/registerServlet", "/login-failed.html"};
        // 获取当前访问的资源路径
        String url = req.getRequestURL().toString();

        System.out.println(url);

        if (url.equals("http://localhost:8080/request-demo/") || url.equals("http://8.134.149.174:8080/request-demo/")) {

            System.out.println(1);

            req.getRequestDispatcher("selectAllServlet").forward(req, response);
        }
        else {

            System.out.println(2);

            // 循环判断
            for (String u : urls) {
                if (url.contains(u)) {
                    // 找到了，放行
                    chain.doFilter(request, response);
                    return;
                }
            }

            //1. 判断session中是否有user
            HttpSession session = req.getSession();
            Object user = session.getAttribute("user");

            //2. 判断user是否为null
            if (user != null) {
                // 登录过了，放行
                chain.doFilter(request, response);
            } else {
                // 没有登录，跳转到登录页面
                req.getRequestDispatcher("/login.html").forward(req, response);
            }
        }
    }


    public void init(FilterConfig config) throws ServletException {
    }


    public void destroy() {
    }
}
